package com.bw.user_module.edtuser;

import android.text.TextUtils;

import androidx.room.Room;

import com.blankj.utilcode.util.LogUtils;
import com.bw.base_application_sdk.BaseApplication;
import com.bw.common.entity.NetErroEntity;
import com.bw.common.entity.SaveEntity;
import com.bw.common.mvvm.model.BaseRespository;
import com.bw.network_sdk.ApiConst;
import com.bw.network_sdk.BaseEntity;
import com.bw.network_sdk.HttpType;
import com.bw.network_sdk.NetWorkFactory;
import com.bw.user_module.dao.UserDatabase;
import com.bw.user_module.user.UserEntity;
import com.bw.user_module.user.UserValueEntity;

import java.io.File;
import java.util.List;
import java.util.Map;

import io.reactivex.Maybe;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 编辑用户:
 * 由于当前界面业务中存在文件上传问题:
 * 类似于微信发朋友圈逻辑:先上传用户选择的文件->上传成功前展示灰色蒙版，
 * 上传成功后展示正常图片,
 * 发布信息或者修改信息时直接提交上传完成的文件以及用户信息
 * 上传以及修改用改用户信息分开处理->逻辑校验，文件未上传完成，提示用户进行
 * 等待上传完成，在上传保存用户更改的信息;
 *整体上传:发现用户头像改变后先上传用户头像信息->在上传用户信息
 * 上传完成后在统一提示用户上传完成.
 * ->无论如何修改用户头像只有在保存时才会发生数据请求->上传操作
 * 文件服务器接口限制图片大小,小于200kb->正常手机拍摄原图无任何分辨率设置时
 * ->4-8MB->图片过大，但展示头像部分控件过小，不需要高保真图片；
 * ->流量浪费，传输时间过长，
 * ->如何图片压缩:原生方式:选择保存图片质量以及图片裁剪进行图片的压缩
 *               三方:luban，comple->图片压缩->指定图片大小进行压缩
 * */
public class EdtUserRespository extends BaseRespository {

    //更新用户信息->当前接口只需要token令牌不需要sign签名，接口中sign为用户签名
    public Observable<BaseEntity>requestEdtUser(Map<String,Object>map){
        Observable<UserEntity>observable = NetWorkFactory.factory(HttpType.TOKEN)
                .create(ApiService.class)
                .requestUpdateUser(createBody(map));
        return checkNetWork(observable);
    }

    //上传用户头像
    public Observable<BaseEntity>requestUploadImg(Map<String,Object>map){
        //用户头像本地地址
        String path = (String) map.get("path");
        //头像名称
        String headName = (String) map.get("headName");
        map.remove("path");
        map.remove("headName");
        NetErroEntity erroEntity = new NetErroEntity();
        erroEntity.status = 200;
        erroEntity.message = "图片路径出错";
        if (TextUtils.isEmpty(path)){
            return Observable.just(erroEntity);
        }
        File file = new File(path);
        if (!file.exists()){
            erroEntity.message = "图片不错在";
            return Observable.just(erroEntity);
        }
        RequestBody requestBody = RequestBody.create(
                MediaType.parse(" multipart/form-data"),file);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加要上传的文件的requestbody
        builder.addFormDataPart("file",headName,requestBody);
        //上传文件时添加额外参数
//        builder.addFormDataPart("","");
        MultipartBody multipartBody = builder.build();
        List<MultipartBody.Part>parts = multipartBody.parts();
        Observable<UploadHeadEntity>uploadObservable =
                NetWorkFactory.factory(HttpType.NONE)
                        .create(ApiService.class)
                        .requestUpload(parts);
        Observable<BaseEntity>userObservable =
                uploadObservable.flatMap(
                        new Function<UploadHeadEntity,
                                ObservableSource<? extends BaseEntity>>() {
                            @Override
                            public ObservableSource<? extends BaseEntity> apply(
                                    @NonNull UploadHeadEntity uploadHeadEntity) throws Exception {
                                if (uploadHeadEntity.statuesCode.equals("200")){
                                    //拼接获取图片的接口地址
                                    String iconUrl = ApiConst.LOADURL+headName;
                                    map.put("userIcon",iconUrl);
                                    return requestEdtUser(map);
                                }else {
                                    NetErroEntity netErroEntity = new NetErroEntity();
                                    netErroEntity.status = 200;
                                    netErroEntity.message = "上传失败";
                                    return Observable.just(netErroEntity);
                                }
                            }
                        });
        return userObservable;
    }
    //获取本地缓存用户数据
    public Observable<BaseEntity> queryUser(){
        UserDatabase db = Room.databaseBuilder(BaseApplication.getInstance(),
                UserDatabase.class, "user.db").build();
        Maybe<List<UserValueEntity>> maybe = db.userDao().queryUser();
        Observable<BaseEntity>userValueEntityObservable = maybe.flatMapObservable(
                new Function<List<UserValueEntity>, ObservableSource<? extends BaseEntity>>() {
                    @Override
                    public ObservableSource<? extends BaseEntity> apply(
                            @NonNull List<UserValueEntity> userValueEntities) throws Exception {
                        UserEntity entity = new UserEntity();
                        entity.status = 200;
                        if (userValueEntities == null){
                            entity.message="用户未登录";
                            Observable<UserEntity>userEntityObservable = Observable.just(entity);
                            return functionObservable(userEntityObservable);
                        }
                        if (userValueEntities.size() == 0){
                            entity.message="用户未登录";
                            Observable<UserEntity>userEntityObservable = Observable.just(entity);
                            return functionObservable(userEntityObservable);
                        }
                        entity.message="用户已登录";
                        entity.data = userValueEntities.get(userValueEntities.size()-1);
                        Observable<UserEntity>userEntityObservable = Observable.just(entity);
                        return functionObservable(userEntityObservable);
                    }
                }
        );
        return userValueEntityObservable;
    }

    //更新本地缓存数据
    Observable<BaseEntity>saveUser(UserEntity entity, UserDatabase db){
        LogUtils.e("LoginRepository:saveUser");
        //手动创建被观察者任务,
        //依托于rxjava线程调度，
        //被观察者将在子线程中执行,
        //room增删改查将在子线程执行,
        //当rxjava的被观察者任务执行完成后,需要手动调用
        // 观察着的onnext以及onComplete
        Observable<SaveEntity>observable=
                new Observable<SaveEntity>() {
                    @Override
                    protected void subscribeActual(
                            Observer<? super SaveEntity> observer) {
                        db.userDao().delUser();
                        db.userDao().insertUser(entity.data);
                        SaveEntity saveEntity = new SaveEntity();
                        saveEntity.status = 200;
                        saveEntity.message ="保存成功";
                        observer.onNext(saveEntity);
                        observer.onComplete();
                    }
                };
        return functionObservable(observable);
    }


}
